package cn.doitedu.marketing.engine.buffer;

import cn.doitedu.marketing.engine.beans.EventCombinationCondition;
import cn.doitedu.marketing.engine.gauges.CountGauge;
import cn.doitedu.marketing.engine.gauges.QueryGauges;
import cn.doitedu.marketing.engine.utils.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

/***
 * @author hunter.d
 * @qq 657270652
 * @wx haitao-duan
 * @date 2021/7/26
 **/
@Slf4j
public class BufferManager {
    Jedis jedis;
    CountGauge bufferPutCountGauge;
    CountGauge bufferGetCountGauge;

    public BufferManager(Jedis jedis, QueryGauges queryGauges){
        bufferPutCountGauge = queryGauges.getBufferPutCountGauge();
        bufferGetCountGauge = queryGauges.getBufferGetCountGauge();
        this.jedis = jedis;
    }

    // 插入缓存
    public boolean put(String deviceId,EventCombinationCondition condition,long timeRangeStart,long timeRangeEnd,String value){
        String key = genKey(deviceId, condition, timeRangeStart, timeRangeEnd);
        try {
            log.debug("buffer put,key: {},value: {}",key,value);
            jedis.set(key, value);
            bufferPutCountGauge.inc();
        }catch(Exception e){
            log.error("buffer put failed,may be the redis is unavailable!");
            this.jedis = ConnectionUtils.getRedisConnection();
            return false;
        }
        return true;
    }

    // 获取缓存
    public long getLong(String deviceId,EventCombinationCondition condition,long timeRangeStart,long timeRangeEnd){
        String v = get(deviceId, condition, timeRangeStart, timeRangeEnd);
        long value = 0;
        try {
            value = Long.parseLong(StringUtils.isBlank(v)?v:"0");
        }catch(Exception e){
            log.warn("buffer value convert to long failed, the value return from redis is {}" ,v);
            return -1;
        }
        return value;
    }

    public String get(String deviceId,EventCombinationCondition condition,long timeRangeStart,long timeRangeEnd){
        String key = genKey(deviceId, condition, timeRangeStart, timeRangeEnd);
        try {
            String v = jedis.get(key);
            log.debug("buffer get,key: {},value: {}",key,v);
            bufferGetCountGauge.inc();
            return v;
        }catch(Exception e){
            log.error("buffer get failed,may be the redis is unavailable!");
            this.jedis = ConnectionUtils.getRedisConnection();
            return null;
        }
    }


    // 组装key
    public String genKey(String deviceId,EventCombinationCondition condition,long timeRangeStart,long timeRangeEnd){
        return deviceId+":"+condition.getCacheId()+":"+timeRangeStart+","+timeRangeEnd;
    }


}
